package com.gurid.service.base.handler;

import com.gurid.common.base.result.R;
import com.gurid.common.base.result.ResultCode;
import com.gurid.common.base.util.ExceptionUtils;
import com.gurid.service.base.exception.GuridException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)//接收全局异常
    @ResponseBody //返回json格式
    public R error(Exception e) {
        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    //SQL语法异常
    @ExceptionHandler(BadSqlGrammarException.class)//接收全局异常
    @ResponseBody //返回json格式
    public R error(BadSqlGrammarException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCode.BAD_SQL_GRAMMAR);
    }

    //传入json包异常
    @ExceptionHandler(HttpMessageNotReadableException.class)//接收全局异常
    @ResponseBody //返回json格式
    public R error(HttpMessageNotReadableException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCode.JSON_PARSE_ERROR);
    }

    //传入自定义异常
    @ExceptionHandler(GuridException.class)//接收全局异常
    @ResponseBody
    public R error(GuridException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}
